var express = require('express');
var router = express.Router();
var app = require('../app');
var url = require('url');

router.all('/*', function(req, res, next) {
    if(req.session.model) {
        req.model = req.session.model;
        delete req.session['model'];
    }

    if (req.session.passport.user && req.session.passport.user.auth) {
        req.model.auth.bool = true;
        req.model.auth.name = req.session.passport.user.name;
        req.model.auth.token = req.session.passport.user.key;
    } else {
        req.model.auth.bool = false;
    }

    //req.model.auth.bool = true;
    //req.model.auth.token = 12345;
    
    next();
});

router.get('/', function(req, res) {
    res.render('index', req.model);
});

// Accept the OpenID identifier and redirect the user to their OpenID
// provider for authentication.  When complete, the provider will redirect
// the user back to the application at:
//     /auth
router.get('/auth', app.passport.authenticate('google'));

// The OpenID provider has redirected the user back to the application.
// Finish the authentication process by verifying the assertion.  If valid,
// the user will be logged in.  Otherwise, authentication has failed.
router.get('/authed',
    app.passport.authenticate('google', { successRedirect: '/',
                                    failureRedirect: '/' }));

router.get('/guest', function(req, res) {
    res.render('index', req.model);
});

router.all('/*', function(req, res, next) {
    if(!req.model.auth.bool) {
        res.redirect('/guest');
    } else {
        next();
    }
});

router.all('/*', function(req, res, next) {
    req.model.timer_init_val = 42;
    if(req.model.auth.bool) {
        var path = url.parse(req.url).pathname;
        req.pool.acquire(function(err, conn) {
            conn.call('timers.getTime', 
                { url_: path, token_: req.model.auth.token}, 
                function(err, result) {
                    req.pool.release(conn);
                    req.model.timer_init_val = result.time;
                    next();
            });
        });
    } else {
        next();
    }
});

module.exports = router;